<?php
/**
 * @author jonathan <jo.link.noir@gmail.com>
 * @version 1.0: jo_link_noir
 * @date 14-05-2010
 */
class U1_DAO_Message extends SW_DAO
{
	/**
	 * @param array $ids
	 * @param string $message
	 * @param string $sujet
	 * @param bool $typePlayer = true
	 * @param DateTime $date = null : si null alors = new DateTime('now', new DateTimeZone('Europe/Paris'))
	 */
	static public function send($id, $message, $sujet = '', $typePlayer = true, DateTime $date = null)
	{
		if (!$date)
			$date = new DateTime('now', new DateTimeZone('Europe/Paris'));

		if (false === isset(self::$queries[__METHOD__]))
		{
			self::$queries[__METHOD__] = self::$db->prepare(
				'INSERT INTO message(ref_player, sujet, message, type, date) VALUES(?,?,?,?,?)'
			);
		}

		self::$queries[__METHOD__]->execute(array(
			(int)$id, $sujet, $message, (bool)$typePlayer, $date->format('Y-m-d H:i:s')
		));
	}

	/**
	 * @param int $idPlayer
	 * @param int|array $idMessage
	 */
	static public function delete($idPlayer, $idMessage)
	{
		if (is_array($idMessage))
		{
			foreach ($idMessage as &$id)
				$id = (int)$id;
			$idMessage = implode(',', $idMessage);
		}
		else
			$idPlayer = (int)$idPlayer;

		self::$db->query('DELETE FROM message WHERE ref_player='.$idPlayer.' AND id IN('.$idMessage.')');
	}

	/**
	 * @param int $idPlayer
	 * @param bool $typePlayer = null : si true message des joueurs, si false celui des généraux sinon tous
	 */
	static public function deleteAll($idPlayer, $typePlayer = null)
	{
		return self::$db->query('DELETE FROM message WHERE ref_player='.((int)$idPlayer.((null !== $typePlayer) ? 'AND type='.((bool)$player) : '')));
	}

	/**
	 * @param int $idPlayer
	 * @param bool $typePlayer = false
	 * @param int $limit = 30
	 * @param int $fetchStyle = PDO::FETCH_OBJ
	 * @return PDOStatement : {id, sujet, message, type, date}
	 */
	static public function select($idPlayer, $typePlayer = false, $limit=30, $fetchStyle = PDO::FETCH_OBJ)
	{
		return self::$db->query('SELECT id, sujet, message, type, date FROM message WHERE ref_player='.((int)$idPlayer.((null !== $typePlayer) ? ' AND type='.((bool)$typePlayer) : '')).' LIMIT '.((int)$limit), $fetchStyle);
	}
}